/**
* @depends jquery.ui.js
*/

(function($) {

	$.widget( 'ui.morify', {
		
		_init: function() {
			
			var $this = this;
			this.element.parents().each( function() {
				var o = $(this);
				if( o.css( 'display' ) == 'none' ) {
					o.addClass( 'TmpHidden' );
					o.css( 'display', 'block' );
				}
			} );
			
			var message = this.message = this.element.html();
			var br = /<[BRbr][^>]*>/g;
			var min = 0;
			var max = message.replace( /\n/g, ' ' ).replace( br, "\n" ).length;

			while( this.element.height() > this.options.maxHeight ) {
				
				var medium = Math.ceil((max-min)/2);
				message = message.replace( /\n/g, ' ' );
	                        message = message.replace( br, "\n" );

				f_message = message;
				message = message.substr( min, medium );
				//message = message.replace( /(<[A-Za-z]+[^>]*>|.)$/, '' );

				message = message.replace( /\n/g, '<br />' );
				this.element.html( message );
				if( this.element.height() < this.options.maxHeight ) {
					min += medium
				}
				else {
					max -= medium;	
				}

				if( medium == 0 ) {
					break;
				}
			}
			
			if( this.message != message ) {
				var a = $('<a class="More">See More</a>');
				this.element.append( a );
				a.click( function() {
					$this.element.html( $this.message );
				} );
			}
			
			this.element.parents( '.TmpHidden' ).each( function() {
				var o = $(this);
				o.removeClass( 'TmpHidden' );
				o.css( 'display', null );
			} );
		},
		
		options: {
			maxHeight: 80
		}
		
	} );
	
})(jQuery);
